﻿using BlazorApp.Model;
using BootstrapBlazor.Components;
using Model.Dtos;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace WebApp.Service
{
    public class StudentService : IStudentService
    {
        public QueryResult<Student> QueryList(QueryPageOptions<Dictionary<string, object>>? options)
        {
            QueryResult<Student> queryResult = new QueryResult<Student>();
            int totalCount = 0;
            Dictionary<string, object> SearchModel = options.SearchModel;

            var queryTable = DbScoped.SugarScope.Queryable<Student>("t")
                .WhereIF(SearchModel["Name"] != null, it => SqlFunc.Contains(it.Name, SearchModel["Name"].ToString()))
                .WhereIF(SearchModel["State"] != null, it => it.State == SqlFunc.ToInt32(SearchModel["State"].ToString()))
                .WhereIF(SearchModel["Sex"] != null, it => it.Sex == SqlFunc.ToInt32(SearchModel["Sex"].ToString()))
                .WhereIF(SearchModel["Department"] != null, it => SqlFunc.Contains(it.Department, SearchModel["Department"].ToString()))
                .WhereIF(SearchModel["Address"] != null, it => SqlFunc.Contains(it.Address, SearchModel["Address"].ToString()))
                .WhereIF(SearchModel["Birth_Start"] != null, it => it.Birth >= Convert.ToDateTime(SearchModel["Birth_Start"].ToString()))
                .WhereIF(SearchModel["Birth_End"] != null, it => it.Birth <= Convert.ToDateTime(SearchModel["Birth_End"].ToString()));
            //if (SearchModel.ContainsKey("Birth_Start"))
            //{
            //    queryTable.Where(it => it.Birth >= Convert.ToDateTime(SearchModel["Birth_Start"].ToString()));
            //}
            //if (SearchModel.ContainsKey("Birth_End"))
            //{
            //    queryTable.Where(it => it.Birth <= Convert.ToDateTime(SearchModel["Birth_End"].ToString()));
            //}


            List<Student> list;
            if (options.IsPage)
            {
                list = queryTable.ToPageList(options.PageIndex, options.PageItems, ref totalCount);
            }
            else
            {
                list = queryTable.ToList();
            }
            queryResult.TotalCount = totalCount;
            queryResult.ResultList = list;

            return queryResult;
        }

        public bool Save(Student student)
        {
            bool ret = false;
            int n = DbScoped.SugarScope.Saveable(student).ExecuteCommand();
            if (n == 1)
            {
                ret = true;
            }
            return ret;
        }

        public bool Delete(int[] ids)
        {
            bool ret = false;
            int n = DbScoped.SugarScope.Deleteable<Student>().In(ids).ExecuteCommand();
            if (n == ids.Length)
            {
                ret = true;
            }

            return ret;
        }
    }
}
